package com.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {

    private RabbitTemplate rabbitTemplate;

    public SendMsgController(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    @GetMapping("/send")
    public void send() {
        log.info("当前时间:{},发送一条消息", new Date().toString());
        rabbitTemplate.convertAndSend("X", "XA", "msg-10");
        log.info("当前时间:{},发送一条消息", new Date().toString());
        rabbitTemplate.convertAndSend("X", "XB", "msg-40");
    }

    /* 自定义延迟队列问题
     * 如果第一个消息耗时TTL是20秒，第二个消息TTL是2秒，
     * 那么第二个消息会在第一个消息进入死信队列后才能进入
     */
    @GetMapping("/sendForTime/{time}")
    public void sendForTime(@PathVariable("time") String time) {
        log.info("当前时间:{},发送一条消息", new Date().toString());
        rabbitTemplate.convertAndSend("X", "XC",
                "msg-" + Integer.parseInt(time) / 1000, msg -> {
                    msg.getMessageProperties().setExpiration(time);
                    return msg;
                });
    }

    //基于延迟消息交换机的TTL队列
    @GetMapping("/plugins/{time}")
    public void plugins(@PathVariable("time") String time) {
        log.info("当前时间{},发送一条消息", new Date().toString());
        rabbitTemplate.convertAndSend("delayed.exchange", "delayed.routingKey",
                "msg-" + Integer.parseInt(time) / 1000, msg -> {
                    msg.getMessageProperties().setDelay(Integer.parseInt(time));
                    return msg;
                });
    }

}
